package com.fbinggun.fbinggunutil.API;


import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.List;

/**
 * Bukkit类常用方法(运行指令 获取所在权限组等)
 */
public class BukkitUtil {


    /**
     * 运行指令
     * @param commands 指令列表
     * @param player 玩家
     * @param plugin 运行指令的插件
     */
    public static void runCommands(List<String> commands,Player player, Plugin plugin){
        for(String command:commands){
            runCommand(command,player,plugin);
        }
    }
    /**
     * 运行指令
     * @param command 指令列表
     * @param player 玩家
     * @param plugin 运行指令的插件
     */
    public static void runCommand(String command, Player player, Plugin plugin){
        String str = command;
        str=str.replaceAll("&","§");
        str=str.replaceAll("%player%",player.getName());
        str=str.replaceAll("%Player%",player.getName());
        str=str.replaceAll("%p%",player.getName());
        if(PluginUtil.isPlaceholderAPI()) {
            str = PApiUtil.setPlaceholders(player, str);
        }

        CommandSender sender = Bukkit.getServer().getConsoleSender();
        if(str.startsWith("[Player]")){
            sender=player;
            str=str.replace("[Player]","");
        }else if(str.startsWith("[CMD]")){
            str=str.replace("[CMD]","");
            sender=Bukkit.getServer().getConsoleSender();
        }
        String s = str;
        CommandSender finalSender = sender;
        new BukkitRunnable() {
            @Override
            public void run() {
                Bukkit.dispatchCommand(finalSender, s);
            }
        }.runTask(plugin);

    }

    /**
     * 获取玩家所在权限组
     * @param player 玩家
     * @return 权限组名
     */
    public static String getPlayerGroup(Player player){
        net.milkbowl.vault.permission.Permission permission =Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class).getProvider();
       return permission.getPrimaryGroup(player);
    }



}
